package com.xk.cart.interceptors;

import com.hy.common.utils.CookieUtils;
import com.xk.auth.entiy.UserInfo;
import com.xk.auth.utils.JwtUtils;
import com.xk.cart.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class CartInterceptor implements HandlerInterceptor {
    private JwtProperties prop;
    public CartInterceptor(JwtProperties prop){
        this.prop=prop;
    }
    //定义一个线程域，存放登录用户
    private final static ThreadLocal<UserInfo> t1=new ThreadLocal<>();
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获得cookie
        String token = CookieUtils.getCookieValue(request, prop.getCookieName());
        //解析token
        try {
            UserInfo user = JwtUtils.getInfoFromToken(token, prop.getPublicKey());
            //request.setAttribute("user",user);
            //将user传递给controller使用
            t1.set(user);
            return true;//true放行，false拦截

        }catch (Exception e){
            log.error("解析用户身份失败");
            return false;
        }
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //后置拦截
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        //页面渲染出来才拦截,是最后执行的方法
        t1.remove();//释放线程
    }
    //获得线程中用户信息的方法，便于在controller或service调用就可以得到user了
    public static UserInfo getUser(){
        return t1.get();
    }

}
